<template>
  <div v-drag class="user-card">
    <el-card style="max-width: 500px; max-height: 500px" shadow="hover">
      <template #header>
        <p>用户管理 <span @mousedown.stop @click="close">x</span></p>
      </template>
      <div class="top">
        <el-button @mousedown.stop @click.prevent="dialogVisible = true"
          ><el-icon style="transform: rotate(45deg)" :size="15" color="blue"><CloseBold /></el-icon>新增用户</el-button
        >
        <div class="right">
          <!-- 回车和失去焦点进行搜索 -->
          <el-input
            @mousedown.stop
            v-model="keyword"
            @keyup.enter.native="handleSearchLike"
            @blur="handleSearchLike"
            placeholder="搜索用户"
            style="width: 160px"
          ></el-input>
          <el-button @mousedown.stop @click.prevent="refresh"
            ><el-icon :size="20"><Refresh /></el-icon
          ></el-button>
          <el-button @mousedown.stop @click.prevent="exportTable"
            ><el-icon :size="20"><Upload /></el-icon
          ></el-button>
        </div>
      </div>
      <div class="table">
        <el-table :data="paginatedData" style="width: 100%" stripe border>
          <el-table-column prop="index" label="序号" width="60"></el-table-column>
          <el-table-column prop="username" label="用户名" width="130"></el-table-column>
          <el-table-column prop="userType" label="用户类型" width="130"></el-table-column>
          <el-table-column prop="loginStatus" label="登录状态" width="130">
            <template #default="scope">
              <span v-if="scope.row.userType === '管理员' && scope.row.loginStatus === '在线中'">正在登录</span>
              <span v-else>{{ scope.row.loginStatus }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <span v-if="scope.row.userType !== '管理员'">
                <el-button class="edit" type="primary" @mousedown.stop @click.prevent="editUser(scope.row)">修改</el-button>
                <el-button class="delete" type="danger" @mousedown.stop @click.prevent="deleteUser(scope.row)">注销</el-button>
                <el-button class="offline" type="warning" @mousedown.stop @click.prevent="offlineUser(scope.$index)" v-if="scope.row.loginStatus === '在线中'"
                  >下线</el-button
                >
              </span>
              <!-- 如果是管理员，只显示下线按钮 -->
              <span v-else>
                <el-button class="offline" type="warning" @mousedown.stop @click.prevent="offlineUser(scope.$index)" v-if="scope.row.loginStatus === '在线中'"
                  >下线</el-button
                >
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination
          @mousedown.stop
          background
          :page-size="pageSize"
          :total="filteredTableData.length"
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
        />
      </div>
    </el-card>
    <!-- 新增用户/修改用户Dialog对话框 -->
    <el-dialog
      width="400px"
      v-model="dialogVisible"
      :title="rowIndex === null ? '新增交通部门用户' : '修改用户'"
      draggable
      @close="handleCloseDialog"
    >
      <el-form :rules="rules" :model="ruleForm" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input @mousedown.stop v-model="ruleForm.username" autocomplete="off" placeholder="请输入账号(不能为空)" />
        </el-form-item>
        <el-form-item @mousedown.stop label="密码" prop="password">
          <el-input v-model="ruleForm.password" show-password autocomplete="off" placeholder="请输入密码(最多不超过18位)" />
        </el-form-item>
        <el-form-item style="margin: 0 0 -10px 228px">
          <el-button @click="handleDialogVisible">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 确认删除用户Dialog对话框 -->
    <el-dialog v-model="deleteDialogVisible" width="400px" draggable align-center @close="handleCloseDialog">
      <span>确认注销该用户？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteSubmit"> 删除 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { h, ref, onMounted, computed } from 'vue';
import { CloseBold, Refresh, Upload } from '@element-plus/icons-vue';
import { de, el } from 'element-plus/es/locales.mjs';
import {
  getUserByUsername,
  getAllUser,
  addTrafficUser,
  updateUser,
  searchUserLike,
  deleteUserByUsername,
} from '@/api/userManageRequest.js';
import { ElMessage } from 'element-plus';
import { logout } from '@/api/userRequest.js';
import { useRouter } from 'vue-router';
import * as XLSX from 'xlsx';

const router = useRouter();

const keyword = ref('');
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const rowIndex = ref(null);
const form = ref(null);
const deleteUsername = ref('');
const currentPage = ref(1); // 当前页码，默认为1
const pageSize = ref(5); // 每页显示的条数，默认为10

//表单验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入账号(不能为空)', trigger: 'blur' },
    { min: 1, max: 9, message: '用户名长度为1-8', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码(最多不超过18位)', trigger: 'blur' },
    { min: 3, max: 18, message: '密码长度为6-18位', trigger: 'blur' },
  ],
});
const ruleForm = ref({
  username: '', //操作行的用户名
  password: '', //操作行的用户密码
  userId: '', //数据库中用户id
});

const tableData = ref([]);

// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredTableData.value.slice(start, end);
});

// 计算筛选后的数据
const filteredTableData = computed(() => {
  if (keyword.value) {
    return tableData.value.filter(item => item.username.toLowerCase().includes(keyword.value.toLowerCase()));
  }
  return tableData.value;
});

// 切换页码时调用
const handleCurrentChange = newPage => {
  currentPage.value = newPage;
};

// 新增用户/修改用户
const handleAddSubmit = async () => {
  try {
    // 触发表单验证
    const valid = await form.value.validate();
    if (!valid) {
      // 表单验证失败时提示用户
      ElMessage.error('请检查表单填写是否正确');
      return;
    }

    // 实现新增/修改用户逻辑
    if (rowIndex.value === null) {
      // 实现新增交通部门用户逻辑
      await addTrafficUser(ruleForm.value)
        .then(result => {
          if (result) {
            // 新增成功时提示用户并重置表单
            ElMessage.success('新增用户成功');
            ruleForm.value = {
              username: '',
              password: '',
            };
            // 关闭对话框
            dialogVisible.value = false;
          } else {
            // 新增失败时提示用户
            ElMessage.error('新增用户失败');
          }
        })
        .catch(error => {
          ElMessage.error(error.response.data);
        });
    } else {
      // 实现修改用户逻辑
      await updateUser(ruleForm.value)
        .then(result => {
          if (result) {
            // 修改成功时提示用户并重置表单
            ElMessage.success('修改用户成功');
            ruleForm.value = {
              username: '',
              password: '',
            };
            // 关闭对话框
            dialogVisible.value = false;
            rowIndex.value = null;
          } else {
            // 修改失败时提示用户
            ElMessage.error('修改用户失败');
          }
        })
        .catch(error => {
          ElMessage.error(error.response.data);
        });
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确');
  }
};

const editUser = async row => {
  // 弹出修改用户Dialog对话框
  rowIndex.value = row.index;
  dialogVisible.value = true;
  const res = await getUserByUsername(row.username);
  // 回填表单数据
  ruleForm.value = {
    username: res.username,
    password: res.password,
    userId: res.id,
  };
};

const deleteUser = row => {
  // 实现删除用户逻辑
  // console.log('删除用户', row);
  deleteDialogVisible.value = true;
  deleteUsername.value = row.username;
};

const refresh = async () => {
  // 刷新用户列表数据
  const result = await getAllUser();
  tableData.value = result.map((item, index) => {
    return {
      index: index + 1,
      username: item.username,
      userType: item.userType,
      loginStatus: item.loginStatus,
    };
  });
};

const handleSearchLike = async () => {
  // 实现模糊搜索逻辑
  await searchUserLike(keyword.value)
    .then(result => {
      tableData.value = result.map((item, index) => {
        return {
          index: index + 1,
          username: item.username,
          userType: item.userType,
          loginStatus: item.loginStatus,
        };
      });
    })
    .catch(error => {
      ElMessage.error(error.response.data);
    });

  // 重置关键字
  keyword.value = '';
};

const handleDeleteSubmit = async () => {
  // 实现删除用户逻辑
  await deleteUserByUsername(deleteUsername.value)
    .then(result => {
      if (result) {
        // 删除成功时提示用户并刷新用户列表
        ElMessage.success('注销用户成功');
        tableData.value = tableData.value.filter(item => item.username !== deleteUsername.value);
        // 关闭对话框
        deleteDialogVisible.value = false;
      } else {
        // 删除失败时提示用户
        ElMessage.error('删除用户失败');
      }
    })
    .catch(error => {
      ElMessage.error(error.response.data);
    });
};

const offlineUser = async index => {
  // 实现下线用户逻辑
  const row = tableData.value[index];
  await logout(row.username)
    .then(result => {
      if (result) {
        // 下线成功时提示用户并刷新用户列表
        ElMessage.success('下线成功');
        tableData.value.splice(index, 1);
        //如果用户是管理员，则刷新页面
        if (row.userType === '管理员') {
          localStorage.removeItem('userName'); // 清除本地存储cookie使其跳转到登录页面
          router.push({ name: 'login' });
        }
      } else {
        // 下线失败时提示用户
        ElMessage.error('下线失败');
      }
    })
    .catch(error => {
      ElMessage.error(error.response.data);
    });
};

// 导出表格为 Excel
const exportTable = () => {
  const worksheet = XLSX.utils.json_to_sheet(tableData.value);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '用户列表');
  XLSX.writeFile(workbook, '用户列表.xlsx');
};

const close = () => {
  document.querySelector('.user-card').style.display = 'none';
};

const handleDialogVisible = () => {
  // 关闭对话框
  dialogVisible.value = false;
  // 重置表单
  ruleForm.value = {
    username: '',
    password: '',
  };
  // 重置索引
  rowIndex.value = null;
};

onMounted(async () => {
  // 加载用户列表数据
  const result = await getAllUser();
  tableData.value = result.map((item, index) => {
    return {
      index: index + 1,
      username: item.username,
      userType: item.userType,
      loginStatus: item.loginStatus,
    };
  });
});
</script>

<style lang="scss" scoped>
.user-card {
  position: absolute;
  width: 692px;
  z-index: 99;
  top: 10%;
  left: 50%;
  transform: translateX(-50%);

  :deep(.el-card) {
    width: 100%;
    max-width: unset !important;

    .el-card__header {
      border-bottom: none !important;
      padding: 5px;

      p {
        padding: 5px 0px;
        margin: 0 15px;
        border-bottom: 1px solid #e4e4e4;
        font-weight: 900;
        border-radius: 5px;
      }

      span {
        margin-left: 570px;
        color: black;
        cursor: pointer;
        font-weight: 400;
      }
    }
  }

  .top {
    display: flex;
    margin-bottom: 10px;

    .right {
      margin-left: 323px;

      .el-button {
        margin-left: 10px;
      }
    }
  }

  .table {
    width: 100%;

    :deep(.el-table--fit) {
      .el-table__inner-wrapper .el-table__header-wrapper {
        margin: 0 auto;

        .el-table__header {
          .el-table__cell div {
            text-align: center;
          }
        }
      }

      .el-table__body-wrapper {
        .cell {
          text-align: center;
        }
      }
    }
  }

  .page {
    width: 100%;
    margin-top: 10px;

    .el-pagination {
      width: 100%;
      align-items: center;
      justify-content: center;
    }
  }
}

.el-button {
  padding: 5px;
}

:deep(.el-dialog) {
  .el-form-item {
    font-weight: 900;
  }

  .el-dialog__title {
    font-weight: 900;
  }
}
</style>
